var express = require('express');
var swig = require('swig');
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var Cookies = require('cookies');
var User = require('./models/user');


var app = express();
//设置swig页面不缓存
swig.setDefaults({
    cache: false
})
//配置cookies
app.use(function (req, res ,next) {
    req.cookies = new Cookies(req,res);
    //解析登录用户的cookies
    req.userInfo = {};
    if (req.cookies.get('userInfo')) {
        try {
            req.userInfo = JSON.parse(req.cookies.get('userInfo'));
            //获取用户登录类型
            User.findById(req.userInfo._id).then(function (userInfo) {
                req.userInfo.isAdmin = Boolean(userInfo.isAdmin);
                req.userInfo.username = userInfo.username;
                next();
            })
        } catch (e){
            next();
        }
    }else {
        next();
    }
});
//当请求的/public时候,自动指引到__dirname + '/public'下对应的文件返回给前端;
app.use('/public', express.static(__dirname + '/public'));//设置静态库
app.set('view cache', false); //设置不缓存
app.set('views','./views/'); //设置模版存放位置
app.set('view engine','html');//注册模版引擎
app.engine('html', swig.renderFile);//定义当前应用使用的模版引擎,使用swig.renderFile方法解后缀为html文件(1.模版名称,2.解析模版的方法)

//根据不同的功能划分模块
app.use(bodyParser.urlencoded({extended:true}));//中间bodyparser配置,会在res下增加一个属性,要先添加
app.use('/admin',require('./router/admin'));
app.use('/api',require('./router/api'));
app.use('/',require('./router/main'));


mongoose.connect('mongodb://localhost:27018/blog',function (err) {
    if (err) {
        console.log('连接数据库失败');
    }else {
        console.log('连接数据库成功');
        //服务器启动监听
        app.listen(3000);
        console.log('server is started at http://localhost:3000');
    }
});


